package com.jeans.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.jeans.model.Cliente;

public class ClienteDAO {
	
	private static ClienteDAO instance = new ClienteDAO();
	
	protected ClienteDAO(){}
	
	public static ClienteDAO getInstance(){
		return instance;
	}
	
	public List<Cliente> getAll() throws Exception{
		
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		
		List<Cliente> clientes = new ArrayList<Cliente>();
		
		try {
		
			conn = getConnection();
			st = conn.createStatement();
			
			// nenhuma instrucao de ordenacao utilizada
			rs = st.executeQuery("select * from Clientes");
			
			while (rs.next()){
				Cliente cliente = new Cliente(
				rs.getString("nome"),
				rs.getString("telefone"),
				rs.getString("email"),
				rs.getInt("id")
				);
				
				clientes.add(cliente);
			}
			
			return clientes;
			
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			closeResources(conn, st, rs);
		}
		
	}
	
	public Connection getConnection() throws Exception{
		
		String databaseURL = "jdbc:mysql://localhost:3306/ordenacao";
		String databaseUser = "root";
		String databasePassword = "";
		Connection conn = null;
		
		try{
			
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(databaseURL, databaseUser, databasePassword);
			
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		return conn;
	}
	
	
	public void closeResources(Connection conn, Statement st, ResultSet rs){
		try {
			
			if(conn != null) conn.close();
			if(st != null) st.close();
			if(rs != null) rs.close();
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	

}
